const db = uniCloud.database();
const dbCmd = db.command;
module.exports = async function(event, context, name) {
	let time1 = Date.now();
	//event为客户端上传的参数
	const dbName = "vk-test";
	let res = {};
	if (event.action == "kong") {
		// 不执行其他逻辑
	} else if (event.action == "db-1") {
		res = await db.collection(dbName).aggregate().sample({ size: 1 }).end()
	} else if (event.action == "db-2") {
		res.db1 = await db.collection(dbName).doc('001').update({
			moeny: dbCmd.inc(-1)
		});
		res.db2 = await db.collection(dbName).doc('002').update({
			moeny: dbCmd.inc(1)
		});
	} else if (event.action == "db-5") {
		res.db1 = await db.collection(dbName).aggregate().sample({ size: 1 }).end()
		res.db2 = await db.collection(dbName).aggregate().sample({ size: 1 }).end()
		res.db3 = await db.collection(dbName).aggregate().sample({ size: 1 }).end()
		res.db4 = await db.collection(dbName).aggregate().sample({ size: 1 }).end()
		res.db5 = await db.collection(dbName).aggregate().sample({ size: 1 }).end()
	} else if (event.action == "db-transaction-2") {
		const transaction = await db.startTransaction()
		try {
			if (name === "B") {
				res.db1 = await transaction.collection(dbName).doc('001').update({
					moeny: dbCmd.inc(-1)
				});
				res.db2 = await transaction.collection(dbName).doc('002').update({
					moeny: dbCmd.inc(1)
				});
			} else {
				// 此处003 004 是为了不和上面的001 002 冲突
				res.db1 = await transaction.collection(dbName).doc('003').update({
					moeny: dbCmd.inc(-1)
				});
				res.db2 = await transaction.collection(dbName).doc('004').update({
					moeny: dbCmd.inc(1)
				});
			}
			await transaction.commit()
		} catch (err) {
			console.log('err: ', err)
			await transaction.rollback();
			throw err
		}
	}
	let time2 = Date.now();
	res.time = time2 - time1;
	console.log("time", res.time);
	return res;
}
